package com.duoketech.service.weixin.cart;

import com.duoketech.exception.ValidateException;
import com.duoketech.model.cart.Cart;
import com.duoketech.model.order.Order;
import com.duoketech.model.orderitem.OrderItem;
import com.duoketech.model.product.Product;
import com.duoketech.model.receiver.Receiver;
import com.duoketech.service.deliveryconfig.DeliveryConfigService;
import com.duoketech.service.weixin.ReceiverService;
import com.duoketech.service.weixin.product.WxProductService;
import com.duoketech.utils.PageUtil;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import org.apache.commons.lang3.StringUtils;

import java.util.*;

public class WxCartService {

    public static  WxCartService ME= new WxCartService();
    public List<Cart> queryCartItemOfMine(int memberId){
        String sql="select t1.*,t2.name,t2.desc,t2.cover,t2.price,t2.is_post from "+Cart.dao.tableName()+" t1,"+Product.dao.tableName()+" t2 where t1.status=? and t1.member_id=? and t1.product_id = t2.id order by t1.id desc";

        List<Cart> cartList= Cart.dao.find(sql,Cart.STATUS_NORMAL,memberId);
        for(Cart o:cartList){
            o.set(Cart.PRICE,o.price());
            String isPost = (o.getInt("is_post")==0)?"不包邮":"包邮";
            o.put(Product.IS_POST,isPost);
        }
        return cartList;
    }


    public void doAddCart(int projectId,int memberId) throws ValidateException {
        Product product = WxProductService.ME.queryProduct(projectId);
        if(product==null){
            throw new ValidateException("当前产品信息不存在");
        }
        Cart cart = new Cart();
        int num=1;
        Cart temp = getCart(projectId, memberId);

        if(temp!=null){
            num = temp.getInt(Cart.NUM)+1;
            cart.set(Cart.NUM,num);
            cart.set(Cart.ID,temp.getInt(Cart.ID));
            cart.set(Cart.PRICE,product.getInt(Product.PRICE));
            cart.set(Cart.TOTAL_PRICE,product.getInt(Product.PRICE)*num);


            //检查当前商品是不是包邮，如果是包邮，则不记重量
            int isPost = product.getInt(Product.IS_POST);
            if(isPost==Product.POST_NO){
                cart.set(Cart.TOTAL_WEIGHT,product.getInt(Product.WEIGHT)*num);
                cart.set(Cart.IS_POST,Product.POST_NO);
            }else{
                cart.set(Cart.TOTAL_WEIGHT,0);
                cart.set(Cart.IS_POST,Product.POST_YES);
            }
            cart.set(Cart.STATUS,Cart.STATUS_NORMAL);
            cart.set(Cart.PRODUCT_ID,product.getInt(Product.ID));
            cart.set(Cart.MEMBER_ID,memberId);
            cart.set(Cart.MODIFY_TIME,new Date());
            cart.update();
        }else{
            cart.set(Cart.NUM,num);
            cart.set(Cart.PRICE,product.getInt(Product.PRICE));
            cart.set(Cart.TOTAL_PRICE,product.getInt(Product.PRICE)*num);
            //检查当前商品是不是包邮，如果是包邮，则不记重量
            int isPost = product.getInt(Product.IS_POST);
            if(isPost==Product.POST_NO){
                cart.set(Cart.TOTAL_WEIGHT,product.getInt(Product.WEIGHT)*num);
                cart.set(Cart.IS_POST,Product.POST_NO);
            }else{
                cart.set(Cart.IS_POST,Product.POST_YES);
                cart.set(Cart.TOTAL_WEIGHT,0);
            }
            cart.set(Cart.STATUS,Cart.STATUS_NORMAL);
            cart.set(Cart.CREATE_TIME,new Date());
            cart.set(Cart.PRODUCT_ID,product.getInt(Product.ID));
            cart.set(Cart.MEMBER_ID,memberId);
            cart.save();
        }


    }

    public void doDescreaseCart(int projectId,int memberId) throws ValidateException {
        Product product = WxProductService.ME.queryProduct(projectId);
        if(product==null){
            throw new ValidateException("当前产品信息不存在");
        }
        Cart cart = new Cart();
        int num=1;
        Cart temp = getCart(projectId, memberId);
        if(temp!=null){
            num = temp.getInt(Cart.NUM)-1;
            num = (num==0)?1:num;
            cart.set(Cart.NUM,num);
            cart.set(Cart.ID,temp.getInt(Cart.ID));
            cart.set(Cart.PRICE,product.getInt(Product.PRICE));
            cart.set(Cart.TOTAL_PRICE,product.getInt(Product.PRICE)*num);
            cart.set(Cart.TOTAL_WEIGHT,product.getInt(Product.WEIGHT)*num);
            cart.set(Cart.STATUS,Cart.STATUS_NORMAL);
            cart.set(Cart.PRODUCT_ID,product.getInt(Product.ID));
            cart.set(Cart.MEMBER_ID,memberId);
            cart.set(Cart.MODIFY_TIME,new Date());
            cart.update();
        }
    }

    public Cart getCart(int projectId, int memberId) {
        String sql="select * from "+Cart.dao.tableName()+" where product_id=? and member_id=? limit 1";
        return Cart.dao.findFirst(sql,projectId,memberId);
    }

    public List<Cart> queryCartItemByMemberId(int memberId){
        String sql="select * from "+Cart.dao.tableName()+" where status=? and member_id=?";
        return Cart.dao.find(sql,Cart.STATUS_NORMAL,memberId);
    }
    
    public List<Cart> queryCartItemByIds(String ids ,int memberId){
        String sql="select * from "+Cart.dao.tableName()+" where status=? and member_id=? and id in("+ids+")";
        return Cart.dao.find(sql,Cart.STATUS_NORMAL,memberId);
    }


    public Map<String,Object> caculateTotal(List<Cart> carts){
        Map<String,Object> result = new HashMap<String,Object>();
        int totalFee = 0;
        int totalNum = 0;
        int totalWeight = 0;
        for(Cart c:carts){
            totalFee +=c.getInt(Cart.TOTAL_PRICE);
            totalNum +=c.getInt(Cart.NUM);
            totalWeight +=c.getInt(Cart.TOTAL_WEIGHT);
        }
        result.put("totalFee",totalFee);
        result.put("totalNum",totalNum);
        result.put("totalWeight",totalWeight);
        return result;
    }

    public int generatorOrder(int memberId,int receiverId,int deliveryType,String ids) throws ValidateException {
        Receiver receiver = Receiver.dao.findById(receiverId);
        if(receiver==null){
            throw new ValidateException("请选择一个默认收货地址");
        }

        if(deliveryType<0){
            throw new ValidateException("请选择一个配送方式");
        }
        List<Cart> cartList = queryCartItemByIds(ids,memberId);
        if(cartList.isEmpty()){
            throw new ValidateException("购物车里没有商品，无法结算");
        }
        List<OrderItem> orderItems = new ArrayList<OrderItem>();
        Map<String,Object> result = caculateTotal(cartList);
        Order order = new Order();
        order.set(Order.STATUS,Order.STATUS_UNPAY);
        order.set(Order.TOTAL_FEE,result.get("totalFee"));
        order.set(Order.TOTAL_WEIGHT,result.get("totalWeight"));
        order.set(Order.TOTAL_NUM,result.get("totalNum"));
        order.set(Order.ADDRESS,receiver.getStr(Receiver.AREA_DETAIL));

        //计算快递费用信息
        String province = receiver.getStr(Receiver.PROVINCE_CODE);
        int totalWeight_G= (int)result.get("totalWeight");
        double deliveryFee = DeliveryConfigService.ME.caculateDeliveryFee(totalWeight_G,province,deliveryType);

        order.set(Order.DELIVERY_FEE,deliveryFee);
        order.set(Order.MEMBER_ID,memberId);
        order.set(Order.UNIT_ID,999999);
        order.set(Order.CREATE_TIME,new Date());
        order.set(Order.NAME,receiver.getStr(Receiver.NAME));
        order.set(Order.MOBILE,receiver.getStr(Receiver.MOBILE));
        order.set(Order.ORDER_SER,System.currentTimeMillis()+"");
        order.set(Order.DELIVERY_TYPE,deliveryType);
        order.save();
        clearCart(memberId,ids);
        //增加所有购物车的东西至 OrderItem 表中
        for(Cart cart:cartList){
            OrderItem orderItem = new OrderItem();
            orderItem.set(OrderItem.NUM,cart.getInt(Cart.NUM));
            orderItem.set(OrderItem.PRICE,cart.getInt(Cart.PRICE));
            orderItem.set(OrderItem.TOTAL_PRICE,cart.getInt(Cart.TOTAL_PRICE));
            orderItem.set(OrderItem.TOTAL_WEIGHT,cart.getInt(Cart.TOTAL_WEIGHT));
            orderItem.set(OrderItem.STATUS,cart.getInt(Cart.STATUS));
            orderItem.set(OrderItem.CREATE_TIME,new Date());
            orderItem.set(OrderItem.PRODUCT_ID,cart.getInt(Cart.PRODUCT_ID));
            orderItem.set(OrderItem.MEMBER_ID,memberId);
            orderItem.set(OrderItem. ORDER_ID,order.getInt(Order.ID));
            orderItem.set(OrderItem. IS_POST,cart.getInt(Cart.IS_POST));
            orderItems.add(orderItem);
        }
        Db.batchSave(orderItems,orderItems.size());



        return order.getInt(Order.ID);
    }

    public void clearCart(int memberId){

        String sql="delete from "+Cart.dao.tableName()+" where member_id = ?";
        Db.update(sql,memberId);
    }
    
    public void clearCart(int memberId,String ids){

        String sql="delete from "+Cart.dao.tableName()+" where member_id = ? and id in("+ids+")";
        Db.update(sql,memberId);
    }


    public void payOrderCallBack(int orderId,int memberId){
        Order order = Order.dao.findById(orderId);
        if(order.getInt(Order.STATUS)==Order.STATUS_UNPAY && order.getInt(Order.MEMBER_ID)==memberId){
            order.set(Order.STATUS,Order.STATUS_PAID);
            order.set(Order.MODIFY_TIME,new Date());
            order.update();
        }
    }


    public void delCartItem(String ids) throws ValidateException {
        if(StringUtils.isEmpty(ids)){
            throw new ValidateException("请选择需要删除的物品");
        }
        String sql="delete from "+Cart.dao.tableName()+" where id in ("+ids+")";
        Db.update(sql);
    }

}
